from elasticsearch import helpers

class ElasticsearchManager:
    @staticmethod
    def es_sync__from_mongodb(es_client, index_name, mongo_collection):
        """
        es_client: ElasticSearch实例
        index_name: 索引名称
        mongo_collection: MongoDB数据库的集合实例
        """
        def generate_es_actions():# 准备导入到Elasticsearch的数据
            for document in mongo_collection.find({}, projection={'name': True, 'tag': True}):
                doc_id = str(document['_id'])
                key = document['name'] + '\t' + '\t'.join(str(x) for x in document['tag'])
                yield {
                    "_index": index_name,
                    "_id": doc_id,
                    "_source": {
                        "key":key
                    }
                }
        response = helpers.bulk(es_client, generate_es_actions())# 批量同步数据到Elasticsearch
        return response


    @staticmethod
    def es_insert(es_client, index_name, doc_id, name:str, tag:list):
        doc_id = str(doc_id)
        key = name + '\t' + '\t'.join(str(x) for x in tag) # 使用制表符拼接name和tag
        document = {"key":key}
        print(key)
        es_client.index(index=index_name, id=doc_id, body=document)# 如果文档不存在，则创建新文档；如果文档已经存在，则更新该文档
    
    @staticmethod
    def es_update(es_client, index_name, doc_id, name, tag):
        doc_id = str(doc_id)
        key = name + '\t' + '\t'.join(str(x) for x in tag)
        updated_key_value = {"key": key}
        es_client.update(index=index_name, id=doc_id, body={"doc": updated_key_value})
    
    @staticmethod
    def es_delete(es_client, index_name, doc_id):
        doc_id = str(doc_id)
        es_client.delete(index=index_name, id=doc_id)

    @staticmethod
    def es_search_by_key_or_page(es_client, index_name, keyword, page_number=1, page_size=10):
        """
        es_client: ElasticSearch实例
        index_name: 索引名称
        keyword: 查询关键字
        page_number: 想要获得的页数
        page_size: 每一页的大小
        """
        from_ = (page_number - 1) * page_size # 计算分页查询的起始位置
        # 查询条件
        query = {
            "query": {
                "match": {
                    "key": keyword
                }
            },
            "from": from_,
            "size": page_size
        }
        response = es_client.search(index=index_name, body=query) # 执行查询
        doc_hits = response['hits']['hits'] # 查询命中的文档列表
        total_hits = response['hits']['total']['value'] # 总命中数

        return doc_hits, total_hits